/**
 *
 */
package gemini.basic.dao.impl;

import gemini.basic.dao.EventDao;
import gemini.basic.dao.GmnDao;
import gemini.basic.model.AbstractDomain;
import gemini.basic.model.Event;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 *
 *
 */
public class EventDaoImpl extends HibernateDaoSupport implements EventDao {

	private GmnDao gmnDao;

	public void setGmnDao(GmnDao gmnDao) {
		this.gmnDao = gmnDao;
	}

	@Override
	public Event saveOrUpdate(Event event, boolean flush) {
		Event result = null;
		if (flush) {
			result = (Event) gmnDao.saveOrUpdateAndFlush(event);
		} else {
			result = (Event) gmnDao.saveOrUpdate(event);
		}
		return result;
	}

	@Override
	public List<Event> getEventByDistributorCode(String code) {
		DetachedCriteria dtCri = DetachedCriteria.forClass(Event.class);
		dtCri.createAlias("distributor", "dis");

		dtCri.add(Restrictions.eq("dis.code", code));

		List<Object> eventList = gmnDao.findByCriteria(dtCri);

		List<Event> result = null;

		if (eventList != null && !eventList.isEmpty()) {
			result = new ArrayList<Event>(eventList.size());
			Event event = null;
			for (Object ob : eventList) {
				event = (Event) ob;
				result.add(event);
			}
		}

		return result;
	}
	
	@Override
	public Event getById(int id) {
		DetachedCriteria dtCri = DetachedCriteria.forClass(Event.class);

		if (id != AbstractDomain.TRANSIENT_ENTITY_ID) {
			dtCri.add(Restrictions.eq("id", id));
		}

		List<Object> resultList = gmnDao.findByCriteria(dtCri);

		Event result = null;
		
		if (resultList != null && !resultList.isEmpty()) {
			result = (Event) resultList.get(0);
		}
		return result;
	}

	@Override
	public void deleteEvent(int id) {
		Event event = getById(id);
		getHibernateTemplate().delete(event);
	}

}
